use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Arc;

use crate::ftp::session::FtpSession;
use crate::services::AuthManager;
use shared::ftp_protocol::FtpCommand;
use shared::types::{FtpResponse, FtpResponseCode};

#[async_trait]
pub trait FtpCommandHandler: Send + Sync {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse;
}

pub struct CommandProcessor {
    handlers: HashMap<String, Box<dyn FtpCommandHandler>>,
}

impl CommandProcessor {
    pub fn new() -> Self {
        let mut handlers: HashMap<String, Box<dyn FtpCommandHandler>> = HashMap::new();
        
        // 注册基础命令处理器
        handlers.insert("USER".to_string(), Box::new(UserCommandHandler));
        handlers.insert("PASS".to_string(), Box::new(PassCommandHandler));
        handlers.insert("QUIT".to_string(), Box::new(QuitCommandHandler));
        handlers.insert("SYST".to_string(), Box::new(SystCommandHandler));
        handlers.insert("FEAT".to_string(), Box::new(FeatCommandHandler));
        handlers.insert("NOOP".to_string(), Box::new(NoopCommandHandler));
        handlers.insert("PWD".to_string(), Box::new(PwdCommandHandler));
        
        // 注册目录操作命令处理器
        handlers.insert("CWD".to_string(), Box::new(CwdCommandHandler));
        handlers.insert("CDUP".to_string(), Box::new(CdupCommandHandler));
        handlers.insert("MKD".to_string(), Box::new(MkdCommandHandler));
        handlers.insert("RMD".to_string(), Box::new(RmdCommandHandler));
        
        // 注册文件操作命令处理器
        handlers.insert("LIST".to_string(), Box::new(ListCommandHandler));
        handlers.insert("NLST".to_string(), Box::new(NlstCommandHandler));
        handlers.insert("RETR".to_string(), Box::new(RetrCommandHandler));
        handlers.insert("STOR".to_string(), Box::new(StorCommandHandler));
        handlers.insert("APPE".to_string(), Box::new(AppeCommandHandler));
        handlers.insert("DELE".to_string(), Box::new(DeleCommandHandler));
        handlers.insert("SIZE".to_string(), Box::new(SizeCommandHandler));
        handlers.insert("MDTM".to_string(), Box::new(MdtmCommandHandler));
        
        // 注册传输模式命令处理器
        handlers.insert("PASV".to_string(), Box::new(PasvCommandHandler));
        handlers.insert("PORT".to_string(), Box::new(PortCommandHandler));
        handlers.insert("TYPE".to_string(), Box::new(TypeCommandHandler));
        handlers.insert("REST".to_string(), Box::new(RestCommandHandler));
        
        Self { handlers }
    }
    
    pub async fn process_command(command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        let command_name = match command {
            FtpCommand::User(_) => "USER",
            FtpCommand::Pass(_) => "PASS",
            FtpCommand::Quit => "QUIT",
            FtpCommand::Syst => "SYST",
            FtpCommand::Feat => "FEAT",
            FtpCommand::Noop => "NOOP",
            FtpCommand::Pwd => "PWD",
            FtpCommand::Cwd(_) => "CWD",
            FtpCommand::Cdup => "CDUP",
            FtpCommand::Mkd(_) => "MKD",
            FtpCommand::Rmd(_) => "RMD",
            FtpCommand::List(_) => "LIST",
            FtpCommand::Nlst(_) => "NLST",
            FtpCommand::Retr(_) => "RETR",
            FtpCommand::Stor(_) => "STOR",
            FtpCommand::Appe(_) => "APPE",
            FtpCommand::Dele(_) => "DELE",
            FtpCommand::Size(_) => "SIZE",
            FtpCommand::Mdtm(_) => "MDTM",
            FtpCommand::Pasv => "PASV",
            FtpCommand::Port(_) => "PORT",
            FtpCommand::Type(_) => "TYPE",
            FtpCommand::Rest(_) => "REST",
            _ => "UNIMPLEMENTED",
        };
        
        // 检查认证状态（除了USER和QUIT命令）
        if !session.is_authenticated() && !matches!(command, FtpCommand::User(_) | FtpCommand::Quit) {
            return FtpResponse::new(FtpResponseCode::NotLoggedIn, "Please log in first");
        }
        
        let processor = Self::new();
        if let Some(handler) = processor.handlers.get(command_name) {
            handler.handle(command, session).await
        } else {
            FtpResponse::new(FtpResponseCode::CommandNotImplemented, "Command not implemented")
        }
    }
}

// 基础命令处理器实现
struct UserCommandHandler;

#[async_trait]
impl FtpCommandHandler for UserCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::User(username) = command {
            if username.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Username required");
            }
            
            // 存储用户名到会话中，等待PASS命令
            session.set_pending_username(username.clone());
            FtpResponse::new(FtpResponseCode::UserNameOk, "Password required")
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid USER command")
        }
    }
}

struct PassCommandHandler;

#[async_trait]
impl FtpCommandHandler for PassCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Pass(password) = command {
            // 获取待验证的用户名
            let username = match session.get_pending_username() {
                Some(username) => username,
                None => {
                    return FtpResponse::new(FtpResponseCode::BadSequence, "USER command required first");
                }
            };
            
            // 使用认证管理器验证用户
            match session.auth_manager().login(&username, password, 
                session.peer_addr().ip().to_string(), 
                session.peer_addr().port()).await {
                Ok(session_data) => {
                    session.set_authenticated(session_data);
                    session.clear_pending_username();
                    FtpResponse::new(FtpResponseCode::UserLoggedIn, "User logged in")
                }
                Err(_) => {
                    session.clear_pending_username();
                    FtpResponse::new(FtpResponseCode::InvalidUsernameOrPassword, "Invalid username or password")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid PASS command")
        }
    }
}

struct QuitCommandHandler;

#[async_trait]
impl FtpCommandHandler for QuitCommandHandler {
    async fn handle(&self, _command: &FtpCommand, _session: &mut FtpSession) -> FtpResponse {
        FtpResponse::new(FtpResponseCode::ServiceClosing, "Goodbye")
    }
}

struct SystCommandHandler;

#[async_trait]
impl FtpCommandHandler for SystCommandHandler {
    async fn handle(&self, _command: &FtpCommand, _session: &mut FtpSession) -> FtpResponse {
        FtpResponse::new(FtpResponseCode::SystemType, "UNIX Type: L8")
    }
}

struct FeatCommandHandler;

#[async_trait]
impl FtpCommandHandler for FeatCommandHandler {
    async fn handle(&self, _command: &FtpCommand, _session: &mut FtpSession) -> FtpResponse {
        FtpResponse::new(FtpResponseCode::CommandOk, "Features:\r\n PASV\r\n TYPE\r\n SIZE\r\n MDTM\r\n211 End")
    }
}

struct NoopCommandHandler;

#[async_trait]
impl FtpCommandHandler for NoopCommandHandler {
    async fn handle(&self, _command: &FtpCommand, _session: &mut FtpSession) -> FtpResponse {
        FtpResponse::new(FtpResponseCode::CommandOk, "NOOP command successful")
    }
}

struct PwdCommandHandler;

#[async_trait]
impl FtpCommandHandler for PwdCommandHandler {
    async fn handle(&self, _command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        let current_dir = session.current_directory();
        FtpResponse::new(FtpResponseCode::PathnameCreated, &format!("\"{}\" is current directory", current_dir))
    }
}

// 目录操作命令处理器
struct CwdCommandHandler;

#[async_trait]
impl FtpCommandHandler for CwdCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Cwd(path) = command {
            if path.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Path required");
            }

            // 构建目标路径
            let new_path = if path == ".." {
                "/".to_string() // 简化处理，回到根目录
            } else if path.starts_with('/') {
                path.to_string()
            } else {
                format!("{}/{}", session.current_directory(), path)
            };

            // 检查读取权限
            match session.check_permission(shared::types::PermissionType::Read, &new_path).await {
                Ok(true) => {
                    session.set_current_directory(new_path);
                    FtpResponse::new(FtpResponseCode::RequestedFileActionOk, "Directory changed")
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid CWD command")
        }
    }
}

struct CdupCommandHandler;

#[async_trait]
impl FtpCommandHandler for CdupCommandHandler {
    async fn handle(&self, _command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if session.current_directory() == "/" {
            FtpResponse::new(FtpResponseCode::RequestedFileActionOk, "Already at root directory")
        } else {
            // 检查父目录的读取权限
            match session.check_permission(shared::types::PermissionType::Read, "/").await {
                Ok(true) => {
                    session.set_current_directory("/".to_string());
                    FtpResponse::new(FtpResponseCode::RequestedFileActionOk, "Directory changed")
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        }
    }
}

struct MkdCommandHandler;

#[async_trait]
impl FtpCommandHandler for MkdCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Mkd(path) = command {
            if path.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Path required");
            }

            let full_path = if path.starts_with('/') {
                path.to_string()
            } else {
                format!("{}/{}", session.current_directory(), path)
            };

            // 检查写入权限
            match session.check_permission(shared::types::PermissionType::Write, &full_path).await {
                Ok(true) => {
                    // 简化实现，实际应该创建目录
                    FtpResponse::new(FtpResponseCode::PathnameCreated, &format!("\"{}\" directory created", path))
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid MKD command")
        }
    }
}

struct RmdCommandHandler;

#[async_trait]
impl FtpCommandHandler for RmdCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Rmd(path) = command {
            if path.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Path required");
            }

            let full_path = if path.starts_with('/') {
                path.to_string()
            } else {
                format!("{}/{}", session.current_directory(), path)
            };

            // 检查删除权限
            match session.check_permission(shared::types::PermissionType::Delete, &full_path).await {
                Ok(true) => {
                    // 简化实现，实际应该删除目录
                    FtpResponse::new(FtpResponseCode::RequestedFileActionOk, &format!("\"{}\" directory removed", path))
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid RMD command")
        }
    }
}

// 文件操作命令处理器
struct ListCommandHandler;

#[async_trait]
impl FtpCommandHandler for ListCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::List(path) = command {
            let target_path = path.as_deref().unwrap_or(session.current_directory());
            
            // 检查读取权限
            match session.check_permission(shared::types::PermissionType::Read, target_path).await {
                Ok(true) => {
                    // 检查数据连接是否已建立
                    if !session.is_data_connection_ready() {
                        return FtpResponse::new(FtpResponseCode::DataConnectionNotOpen, "Use PASV first");
                    }
                    
                    // 发送数据传输开始响应
                    FtpResponse::new(FtpResponseCode::DataConnectionAlreadyOpen, "Opening ASCII mode data connection for file list")
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid LIST command")
        }
    }
}

struct NlstCommandHandler;

#[async_trait]
impl FtpCommandHandler for NlstCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Nlst(path) = command {
            let target_path = path.as_deref().unwrap_or(session.current_directory());
            
            // 检查读取权限
            match session.check_permission(shared::types::PermissionType::Read, target_path).await {
                Ok(true) => {
                    // 检查数据连接是否已建立
                    if !session.is_data_connection_ready() {
                        return FtpResponse::new(FtpResponseCode::DataConnectionNotOpen, "Use PASV first");
                    }
                    
                    // 发送数据传输开始响应
                    FtpResponse::new(FtpResponseCode::DataConnectionAlreadyOpen, "Opening ASCII mode data connection for name list")
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid NLST command")
        }
    }
}

struct RetrCommandHandler;

#[async_trait]
impl FtpCommandHandler for RetrCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Retr(filename) = command {
            if filename.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Filename required");
            }
            
            let file_path = session.build_file_path(filename);
            
            // 检查读取权限
            match session.check_permission(shared::types::PermissionType::Read, &file_path).await {
                Ok(true) => {
                    // 检查数据连接是否已建立
                    if !session.is_data_connection_ready() {
                        return FtpResponse::new(FtpResponseCode::DataConnectionNotOpen, "Use PASV first");
                    }
                    
                    // 发送数据传输开始响应
                    FtpResponse::new(FtpResponseCode::DataConnectionAlreadyOpen, &format!("Opening ASCII mode data connection for {}", filename))
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid RETR command")
        }
    }
}

struct StorCommandHandler;

#[async_trait]
impl FtpCommandHandler for StorCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Stor(filename) = command {
            if filename.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Filename required");
            }
            
            let file_path = session.build_file_path(filename);
            
            // 检查写入权限
            match session.check_permission(shared::types::PermissionType::Write, &file_path).await {
                Ok(true) => {
                    // 检查数据连接是否已建立
                    if !session.is_data_connection_ready() {
                        return FtpResponse::new(FtpResponseCode::DataConnectionNotOpen, "Use PASV first");
                    }
                    
                    // 发送数据传输开始响应
                    FtpResponse::new(FtpResponseCode::DataConnectionAlreadyOpen, &format!("Opening ASCII mode data connection for {}", filename))
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid STOR command")
        }
    }
}

struct AppeCommandHandler;

#[async_trait]
impl FtpCommandHandler for AppeCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Appe(filename) = command {
            if filename.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Filename required");
            }
            
            let file_path = session.build_file_path(filename);
            
            // 检查写入权限
            match session.check_permission(shared::types::PermissionType::Write, &file_path).await {
                Ok(true) => {
                    // 检查数据连接是否已建立
                    if !session.is_data_connection_ready() {
                        return FtpResponse::new(FtpResponseCode::DataConnectionNotOpen, "Use PASV first");
                    }
                    
                    // 发送数据传输开始响应
                    FtpResponse::new(FtpResponseCode::DataConnectionAlreadyOpen, &format!("Opening ASCII mode data connection for {}", filename))
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid APPE command")
        }
    }
}

struct DeleCommandHandler;

#[async_trait]
impl FtpCommandHandler for DeleCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Dele(filename) = command {
            if filename.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Filename required");
            }
            
            let file_path = session.build_file_path(filename);
            
            // 检查删除权限
            match session.check_permission(shared::types::PermissionType::Delete, &file_path).await {
                Ok(true) => {
                    // 简化实现，实际应该删除文件
                    FtpResponse::new(FtpResponseCode::RequestedFileActionOk, &format!("File {} deleted", filename))
                }
                Ok(false) => {
                    FtpResponse::new(FtpResponseCode::FileNotFound, "Permission denied")
                }
                Err(_) => {
                    FtpResponse::new(FtpResponseCode::LocalError, "Permission check failed")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid DELE command")
        }
    }
}

struct SizeCommandHandler;

#[async_trait]
impl FtpCommandHandler for SizeCommandHandler {
    async fn handle(&self, command: &FtpCommand, _session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Size(filename) = command {
            if filename.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Filename required");
            }
            
            // 简化实现，实际应该返回文件大小
            FtpResponse::new(FtpResponseCode::FileStatusOk, "12345") // 示例文件大小
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid SIZE command")
        }
    }
}

struct MdtmCommandHandler;

#[async_trait]
impl FtpCommandHandler for MdtmCommandHandler {
    async fn handle(&self, command: &FtpCommand, _session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Mdtm(filename) = command {
            if filename.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Filename required");
            }
            
            // 简化实现，实际应该返回文件修改时间
            FtpResponse::new(FtpResponseCode::FileStatusOk, "20240101120000") // 示例时间戳
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid MDTM command")
        }
    }
}

// 传输模式命令处理器
struct PasvCommandHandler;

#[async_trait]
impl FtpCommandHandler for PasvCommandHandler {
    async fn handle(&self, _command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        // 创建被动模式监听器
        match session.create_passive_listener().await {
            Ok(port) => {
                session.set_transfer_mode(shared::types::TransferMode::Passive);
                // 返回PASV响应，格式: Entering Passive Mode (h1,h2,h3,h4,p1,p2)
                let local_ip = "127.0.0.1"; // 简化处理，实际应该获取服务器IP
                let ip_parts: Vec<&str> = local_ip.split('.').collect();
                let p1 = (port >> 8) as u8;
                let p2 = (port & 0xFF) as u8;
                
                let pasv_response = format!(
                    "Entering Passive Mode ({},{},{},{},{},{})",
                    ip_parts[0], ip_parts[1], ip_parts[2], ip_parts[3], p1, p2
                );
                
                FtpResponse::new(FtpResponseCode::EnteringPassiveMode, &pasv_response)
            }
            Err(_) => {
                FtpResponse::new(FtpResponseCode::ServiceNotAvailable, "Failed to create passive connection")
            }
        }
    }
}

struct PortCommandHandler;

#[async_trait]
impl FtpCommandHandler for PortCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Port(addr) = command {
            if addr.is_empty() {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Address required");
            }
            
            // 解析PORT命令的地址格式: h1,h2,h3,h4,p1,p2
            let parts: Vec<&str> = addr.split(',').collect();
            if parts.len() != 6 {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Invalid address format");
            }
            
            // 解析IP地址
            let _ip_str = format!("{}.{}.{}.{}", parts[0], parts[1], parts[2], parts[3]);
            let port = (parts[4].parse::<u16>().unwrap_or(0) << 8) + parts[5].parse::<u16>().unwrap_or(0);
            
            if port == 0 {
                return FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Invalid port number");
            }
            
            // 存储客户端数据连接信息
            session.set_transfer_mode(shared::types::TransferMode::Active);
            session.set_data_port(Some(port));
            
            FtpResponse::new(FtpResponseCode::CommandOk, "PORT command successful")
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid PORT command")
        }
    }
}

struct TypeCommandHandler;

#[async_trait]
impl FtpCommandHandler for TypeCommandHandler {
    async fn handle(&self, command: &FtpCommand, _session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Type(mode) = command {
            match mode.to_uppercase().as_str() {
                "A" | "ASCII" => {
                    FtpResponse::new(FtpResponseCode::CommandOk, "Type set to A")
                }
                "I" | "IMAGE" | "BINARY" => {
                    FtpResponse::new(FtpResponseCode::CommandOk, "Type set to I")
                }
                _ => {
                    FtpResponse::new(FtpResponseCode::ParameterSyntaxError, "Invalid type")
                }
            }
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid TYPE command")
        }
    }
}

struct RestCommandHandler;

#[async_trait]
impl FtpCommandHandler for RestCommandHandler {
    async fn handle(&self, command: &FtpCommand, session: &mut FtpSession) -> FtpResponse {
        if let FtpCommand::Rest(offset) = command {
            session.set_resume_offset(Some(*offset));
            FtpResponse::new(FtpResponseCode::RequestedFileActionOk, &format!("Restarting at {}", offset))
        } else {
            FtpResponse::new(FtpResponseCode::SyntaxError, "Invalid REST command")
        }
    }
}
